using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;
using System.Net.Mail;
using System.Net;
using ctsu.Data;

namespace ctsu.ExceptionHandling
{
    
    public class CremaExceptions
    {
    }

    [ConfigurationElementType(typeof(CustomHandlerData))]
    public class CremaExceptionHandler : IExceptionHandler
    {
        public CremaExceptionHandler(NameValueCollection ignore)
        {
        }


        public Exception HandleException(Exception ex, Guid correlationID)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            
            TextExceptionFormatter tef = new TextExceptionFormatter(sw, ex);
            tef.Format();                        
            
            try
            {
                string errDate = DateTime.Today.ToShortDateString();
                string errText = sb.ToString();
                string sql = "INSERT INTO Exceptions (ErrorDate, ErrorText) Values(@ErrorDate, @ErrorText)";
                SqlParameter[] aParams = new SqlParameter[2];

                aParams[0] = new SqlParameter("@ErrorDate", errDate);
                aParams[1] = new SqlParameter("@ErrorText", errText);

                Database db = DatabaseFactory.CreateDatabase();
                DbCommand cmd = db.GetSqlStringCommand(sql);
                DataAccess.AddParamArrayToDbCommand(cmd, aParams);
                db.ExecuteNonQuery(cmd);


                //SmtpClient client = new SmtpClient("CHEXV1.CHBOSTON.ORG");
                ////SmtpClient client = new SmtpClient("outgoing.verizon.net");            
                ////NetworkCredential nc = new NetworkCredential("vze2vdwc", "sol22lik");
                ////client.Credentials = nc;           
                //string from = "Joe@Childrens.Harvard.edu";
                //MailMessage mm = new MailMessage(from, "joseph.rezuke@childrens.harvard.edu");
                ////MailMessage mm = new MailMessage(from, "j.rezuke@verizon.net");

                //mm.Subject = "CREMA2 - Unexpected Error";
                //mm.Body = sb.ToString();
                //client.Send(mm);

                return ex;
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
                return ex;
            }
        }

    }
}
